package cn.eud.hunau.handler;

import cn.eud.hunau.common.R;
import cn.eud.hunau.common.ResultCodeEnum;
import cn.eud.hunau.exception.BusinessException;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * @author hb
 * @date 2025-06-18 16:53:54
 */
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 处理NoResourceFoundException
     *
     *  application.yml配置文件中配置如下
     *
     *  web:
     *     resources:
     *       add-mappings: true #拒绝默认的404的处理方式
     *   mvc:
     *     problemdetails:
     *       enabled: true
     *
     */

    @ResponseBody
    protected ResponseEntity<Object> handleNoResourceFoundException(NoResourceFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        return new ResponseEntity<>(R.error().code(400404).message(ex.getMessage()),
                status);
    }

    /**
     * SpringBoot3 throw-exception-if-no-handler-found过时之后，NoHandlerFoundException的处理
     *
     * application.yml配置文件中配置如下
     *
     *  web:
     *     resources:
     *       add-mappings: false #拒绝默认的404的处理方式
     *   mvc:
     *     problemdetails:
     *       enabled: true
     *
     */
    @ResponseBody
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        return new ResponseEntity<>(R.error().code(400404).message(ex.getMessage()),
                status);

    }


    private HttpStatus getStatus(HttpServletRequest request) {
        Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        HttpStatus status = HttpStatus.resolve(code);
        return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
    }

    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        e.printStackTrace();//可以使用日志替代
        return R.setResult(ResultCodeEnum.NPE);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public R error(BusinessException e) {
        e.printStackTrace();//可以使用日志替代
        return R.error().code(e.getCode()).message(e.getMessage());
    }

}